import { useEffect, useState } from 'react';
import { useNavigate, useParams } from 'react-router-dom';
import { Button, Card, message, Tag, Row, Col } from 'antd';
import classNames from 'classnames';
import { fetchPatientAPI, fetchScheduleAPI, submitOrderAPI } from '@/api/hospitalAPI/bookingAPI';
import { Patient } from '@/type/bookingType';
import { FindScheduleItem } from '@/type/scheduleType';
import './Booking.scss';


const Booking = () => {

  const navigate = useNavigate();
  // 路由传递过来的参数
  const { scheduleId, hoscode } = useParams();
  // 就诊人列表
  const [patientList, setPatientList] = useState<Patient[]>([]);
  // 排班信息
  const [schedule, setSchedule] = useState<FindScheduleItem>();
  //当前就诊人
  const [patient, setPatient] = useState<Patient>();
  //loading状态
  const [loading, setLoading] = useState<boolean>(false);

  /**
   * @description 根据排班id获取排班数据的回调函数
   * */
  const fetchSchedule = async () => {
    try {
      const { data } = await fetchScheduleAPI(scheduleId as string);
      setSchedule(data);
    } catch (error: any) {
      message.error(error.message);
    }
  };

  /**
   * @description 获取就诊人列表的回调函数
   * */
  const fetchPatient = async () => {
    try {
      const { data } = await fetchPatientAPI();
      setPatientList(data);
      setPatient(data[0]);
    } catch (error: any) {
      message.error(error.message);
    }
  };

  /**
   *@description 修改就诊人的回调函数
   */
  const changePatient = (patient: Patient) => {
    setPatient(patient);
  };

  /**
   * @description 确认挂号的回调函数
   **/
  const handleSubmit = async () => {
    try {
      if (!patient?.id) return message.warning('请选择就诊人');
      setLoading(true);
      const { data } = await submitOrderAPI(hoscode, scheduleId, patient?.id);
      navigate(`/member/orderDetail/${data}`);
      message.success('预约成功');
    } catch (error: any) {
      message.error(error.message);
    } finally {
      setLoading(false);
    }
  };
  /**
  * @description 添加就诊人的回调函数
  * */
  const addPatient = () => {
    navigate('/member/patientForm');
  };

  useEffect(() => {
    Promise.all([fetchSchedule(), fetchPatient()]);
    window.scrollTo(0, 0);
  }, []);

  return (
    <div className="booking">
      <div className="info">
        <h2>确认挂号信息</h2>
      </div>
      <Card hoverable>
        <div className="patient-info">
          <div className="header">
            <i className="iconfont icon-jzrk"></i> <span>选择就诊人:</span> <Button type="primary" onClick={addPatient}>添加就诊人</Button>
          </div>
          <div className="patient-list">
            {
              patientList?.map(item => {
                return (
                  <Card className={classNames(item.id === patient?.id ? 'active' : '')} title={item.name} hoverable style={{ width: 340 }} key={item.id} onClick={() => changePatient(item)}>
                    <p> {item.param.certificatesTypeString} ： {item.certificatesNo || 'xxxxxxxxxx'}</p>
                    <p>更新时间：{item.updateTime}</p>
                    <p>创建时间：{item.createTime}</p>
                    <p>就诊人ID：{item.id}</p>
                    <p>就诊人地址：{item.param.fullAddress}</p>
                    <p>就诊人性别：{item.sex === 0 ? '女' : '男'}</p>
                    <p>出生日期：{item.birthdate}</p>
                    <p>手机号：{item.phone}</p>
                    <p>婚姻状态：{item.isMarry === 0 ? '未婚' : '已婚'}</p>
                  </Card>
                );
              })
            }
          </div>
        </div>
      </Card>
      <Card className="patient-card" hoverable>
        <div className="header">
          <i className="iconfont icon-jiuzhenqia"></i> <span>选择就诊卡:</span>
          <span style={{ color: '#ee1212', fontSize: '13px', marginLeft: '10px' }}>如您持社保卡就诊，请务必选择医保预约挂号，以保证正常医保报销</span>
        </div>
        <div style={{ width: 1000 }} title={`${patient?.name} ${patient?.certificatesNo} 居民身份证`}>
          <div className="card">
            <Tag color="#f50">{patient?.isInsure === 1 ? '医保' : '自费'}</Tag>
            <span>{patient?.certificatesNo} 居民身份证</span>
          </div>
        </div>
      </Card>
      <Card hoverable>
        <div className="register">
          <div className="header">
            <i className="iconfont icon-guahao"></i> <span>挂号信息:</span>
          </div>
          <Row gutter={16}>
            <Col className="gutter-row" span={6}>
              <div>就诊日期：{schedule?.workDate} {schedule?.param.dayOfWeek} {schedule?.workTime === 0 ? '上午' : '下午'}</div>
            </Col>
            <Col className="gutter-row" span={6}>
              <div>就诊医院：{schedule?.param.hosname}</div>
            </Col>
          </Row>
          <Row gutter={16}>
            <Col className="gutter-row" span={6}>
              <div>就诊科室：{schedule?.param.depname}</div>
            </Col>
            <Col className="gutter-row" span={6}>
              <div>医生姓名：{schedule?.docname}</div>
            </Col>
          </Row>
          <Row gutter={16}>
            <Col className="gutter-row" span={5}>
              <div>医生职务：{schedule?.title}</div>
            </Col>
            <Col className="gutter-row" span={20}>
              <div>医生专长:{schedule?.skill}</div>
            </Col>
          </Row>
          <Row gutter={16}>
            <Col className="gutter-row" span={10}>
              <div>医事服务费：<Tag color="#f50">￥{schedule?.amount}</Tag>
              </div>
            </Col>
          </Row>
        </div>
      </Card>
      <Card hoverable>
        <div className="user-info">
          <div className="header">
            <i className="iconfont icon-yonghu"></i> <span>用户信息:</span>
          </div>
          <div className="card">
            <span>就诊人手机号：{patient?.phone}</span>
          </div>
        </div>
      </Card>
      <div className="submit">
        <Button type="primary" size="large" loading={loading} onClick={handleSubmit}>确认挂号</Button>
      </div>
    </div>
  );
};


export default Booking;
